<?php

namespace addons\vip\model;

use addons\shopro\model\Dispatch;
use addons\shopro\model\DispatchSelfetch;
use addons\shopro\model\Goods as GoodsModel;
use addons\shopro\model\OrderItem;
use addons\shopro\model\UserAddress;
use addons\shopro\model\Verify;
use app\common\library\Auth;
use app\common\model\User;
use think\Db;
use think\Hook;
use think\Model;

class Record extends Model
{

    // 表名
    protected $name = 'vip_record';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];

    public function getStatusTextAttr($value, $data)
    {
        $statusArr = [
            'created'  => '待支付',
            'active'   => '生效中',
            'expired'  => '已到期',
            'locked'   => '锁定中',
            'upgraded' => '已升级',
            'finished' => '已结束',
            'canceled' => '已取消'
        ];
        return isset($statusArr[$data['status']]) ? $statusArr[$data['status']] : '未知';
    }

    /**
     * 设定VIP已生效
     * @param int $id VIP记录ID
     * @return bool
     */
    public static function settle($id)
    {
        $recordInfo = self::get($id);
        if (!$recordInfo) {
            return false;
        }
        if ($recordInfo['status'] == 'active') {
            return true;
        }

        //设定过期时间和状态
        $expiretime = time() + $recordInfo['days'] * 86400;

        $lastRecordInfo = self::getLastRecord($recordInfo['user_id']);
        if ($lastRecordInfo) {
            if ($lastRecordInfo['level'] == $recordInfo['level']) {
                //等级相同，直接设置为已完成
                $lastRecordInfo->save(['status' => 'finished']);
                $expiretime = $lastRecordInfo->expiretime + $recordInfo['days'] * 86400;
            } else {
                //等级较低，统一处理
            }
        }

        //变更低等级的过期时间和状态
        Record::where('user_id', $recordInfo['user_id'])
            ->where('level', '<', $recordInfo['level'])
            ->where('status', 'in', ['locked', 'active'])
            ->update(['expiretime' => Db::raw('expiretime+' . ($recordInfo['days'] * 86400)), 'status' => 'locked']);

        $recordInfo->save(['status' => 'active', 'expiretime' => $expiretime]);

        //变更会员VIP等级
        $userInfo = User::get($recordInfo['user_id']);
        if ($userInfo && isset($userInfo['vip'])) {
            $userInfo->save(['vip' => $recordInfo['level']]);
        }

        //发放赠送商品
        if($recordInfo->level > 1){
            $vip = Db::name('vip')->where('level',$recordInfo->level)->field('goods_ids,goods2_ids')->find();
            $goods_ids = '';
            if ($vip['goods_ids'] && $vip['goods2_ids']){
                $goods_ids = $vip['goods_ids'].','.$vip['goods2_ids'];
            }elseif ($vip['goods_ids'] && !$vip['goods2_ids']){
                $goods_ids = $vip['goods_ids'];
            }elseif ($vip['goods2_ids'] && !$vip['goods_ids']){
                $goods_ids = $vip['goods2_ids'];
            }

            if($goods_ids && $recordInfo->address_id){
                $level = $recordInfo->level;
                $goods_arr = explode(',',$goods_ids);
                $log = [];
                foreach ($goods_arr as $k=>$goods_id){
                    $goods = Db::name('shopro_goods')->where('id',$goods_id)->find();
                    if(!$goods){
                        continue;
                    }

                    if(!$goods_id || !$level){
                        continue;
                    }
                    $is_log = Db::name('vip_receive')->where('user_id',$recordInfo->user_id)->where('level',$level)->where('goods_type',$goods['type'])->find();

                    if($is_log){
                        continue;
                    }

                    $user_address = UserAddress::get($recordInfo->address_id);
                    if($goods['type'] != 'virtual' && !$user_address){
                        continue;
                    }

                    $orderData = [];
                    $orderData['order_sn'] = self::getSn($recordInfo->id);
                    $orderData['user_id'] = $recordInfo->user_id;
                    $orderData['type'] = 'goods';
                    $orderData['activity_type'] = '';
                    $orderData['goods_amount'] = $goods['price'];
                    $orderData['dispatch_amount'] = 0;
                    $orderData['total_amount'] = 0;
                    $orderData['score_amount'] = 0;
                    $orderData['total_fee'] = 0;
                    $orderData['discount_fee'] = 0;
                    $orderData['score_fee'] = 0;          // 记录score 支付数
                    $orderData['coupon_fee'] = 0;
                    $orderData['activity_discount_money'] = 0;
                    $orderData['dispatch_discount_money'] = 0;
                    $orderData['goods_original_amount'] = 0;
                    if ($user_address) {
                        $orderData['phone'] = $user_address->phone;
                        $orderData['consignee'] = $user_address->consignee;
                        $orderData['province_name'] = $user_address->province_name;
                        $orderData['city_name'] = $user_address->city_name;
                        $orderData['area_name'] = $user_address->area_name;
                        $orderData['address'] = $user_address->address;
                        $orderData['province_id'] = $user_address->province_id;
                        $orderData['city_id'] = $user_address->city_id;
                        $orderData['area_id'] = $user_address->area_id;
                    }
                    $orderData['status'] = 1;
                    $orderData['pay_type'] = 'vip';
                    $orderData['remark'] = '领取商品';
                    $orderData['ext'] = '';

                    $order = new \addons\shopro\model\Order();
                    $order->allowField(true)->save($orderData);

                    $orderItem = new OrderItem();

                    $orderItem->user_id = $recordInfo->user_id;
                    $orderItem->order_id = $order->id;
                    $orderItem->goods_id = $goods_id;
                    $orderItem->goods_type = $goods['type'];
                    $orderItem->goods_sku_price_id = Db::name('shopro_goods_sku_price')->where('goods_id', $goods['id'])->value('id');

                    $orderItem->goods_title = $goods['title'];
                    $orderItem->goods_image =  $goods['image'];
                    $orderItem->goods_original_price = $goods['original_price'];
                    $orderItem->discount_fee = 0;        // 平均计算单件商品所享受的折扣
                    $orderItem->pay_price = 0;        // 平均计算单件商品不算运费，算折扣时候的金额
                    $orderItem->goods_price = $goods['price'];
                    $orderItem->goods_num =  1;
                    $orderItem->goods_weight = 0;
                    $orderItem->dispatch_status = $goods['type'] == 'virtual' ? 1 : 0;
                    $orderItem->dispatch_fee = 0;
                    $orderItem->dispatch_type = $goods['dispatch_type'];
                    $orderItem->dispatch_id =  $goods['dispatch_ids'];
                    $orderItem->store_id =  0;
                    $orderItem->aftersale_status = 0;
                    $orderItem->comment_status = 0;
                    $orderItem->refund_status = 0;
                    $orderItem->save();
                    $log[] = [
                        'user_id'=>$recordInfo->user_id,
                        'level'=>$level,
                        'createtime'=>time(),
                        'goods_type'=>$goods['type'],
                        'goods_id'=>$goods['id'],
                    ];


                    if($goods['type'] == 'virtual'){
                        // 获取配送模板
                        $dispatch = Dispatch::where('type', $goods['dispatch_type'])->where('id', $orderItem->dispatch_id)->find();
                        $type_ids = $dispatch['type_ids'] ?? '';
                        $dispatch_selfetch_ids = explode(',', $type_ids);
                        $dispatchSelfetch = DispatchSelfetch::where('id', 'in', $dispatch_selfetch_ids)
                            ->order('id', 'asc')->find();

                        $expiretime = null;       // 核销券过期时间
                        if ($dispatchSelfetch) {
                            if ($dispatchSelfetch['expire_type'] == 'day') {
                                $expire_day = $dispatchSelfetch['expire_day'] > 0 ? $dispatchSelfetch['expire_day'] : 0;
                                $expiretime = $expire_day ? (time() + ($expire_day * 86400)) : null;
                            } else {
                                $expiretime = $dispatchSelfetch['expire_time'] ?: null;
                            }
                        }
                        $verify = Db::name('shopro_verify')->insert([
                            'user_id'=>$recordInfo->user_id,
                            'type'=>'verify',
                            'code'=>Verify::getCode(),
                            'order_id'=>$order->id,
                            'order_item_id'=>$orderItem->id,
                            'expiretime'=>$expiretime,
                            'oper_id'=>0,
                            'is_vip'=>1,
                            'createtime'=>time(),
                        ]);
                    }
                }
                if($log){
                    Db::name('vip_receive')->insertAll($log);
                }
            }

        }
        Hook::listen('vip_record_begin', $recordInfo);
    }
    public static function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return $order_sn . $id;
    }

    /**
     * 设定VIP未生效
     * @param int $id VIP记录ID
     * @param string $status 设定状态
     * @return bool
     */
    public static function unsettle($id, $status = 'expired')
    {
        $recordInfo = self::get($id, ['user']);
        if (!$recordInfo) {
            return false;
        }
        if ($recordInfo->status == $status) {
            return true;
        }
        $recordInfo->save(['status' => $status]);
        //匹配锁定未过期的数据
        $lockRecordList = Record::where('status', 'locked')
            ->where('user_id', $recordInfo->user_id)
            ->where('id', '<>', $recordInfo->id)
            ->order('level', 'desc')
            ->select();
        if (count($lockRecordList) > 0) {
            $time = time();
            foreach ($lockRecordList as $subindex => $subitem) {
                if ($subitem['expiretime'] > $time) {
                    $subitem->save(['status' => 'active']);
                    $subitem->user && $subitem->user->save(['vip' => $subitem['level']]);
                    Hook::listen('vip_record_begin', $subitem);
                    break;
                } else {
                    $subitem->save(['status' => 'expired']);
                    $subitem->user && $subitem->user->save(['vip' => 0]);
                    Hook::listen('vip_record_end', $recordInfo);
                }
            }
        } else {
            $recordInfo->user && $recordInfo->user->save(['vip' => 0]);
            Hook::listen('vip_record_end', $recordInfo);
        }
        return true;
    }

    /**
     * 获取最后一条生效中的VIP记录
     * @param int $user_id 会员ID
     * @return array|false|\PDOStatement|string|Model
     */
    public static function getLastRecord($user_id = null)
    {
        $user_id = is_null($user_id) ? Auth::instance()->id : $user_id;
        $lastRecordInfo = Record::where('user_id', $user_id)->where('status', 'active')->order('level', 'desc')->find();
        if ($lastRecordInfo && $lastRecordInfo['expiretime'] < time()) {
            Record::unsettle($lastRecordInfo['id'], 'expired');
            $lastRecordInfo = self::getLastRecord($user_id);
        }
        return $lastRecordInfo;
    }

    public function user()
    {
        return $this->belongsTo('\app\common\model\User', "user_id", "id", [], 'LEFT');
    }

    public function vip()
    {
        return $this->belongsTo('Vip', "vip_id", "id", [], 'LEFT');
    }

}
